package com.its.us.netty.client;

import com.its.us.netty.client.code.StringDecAndEncInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.util.Scanner;

/**
 * @Author: master
 * @Date: 2020/11/1 21:13
 * @Version: 1.0
 */
public class ChatClient {

    private final int port;
    private final String host;

    public ChatClient(int port, String host) {
        this.port = port;
        this.host = host;
    }

    public void run() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bs = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new StringDecAndEncInitializer());
            ChannelFuture channelFuture = bs.connect(host, port).sync();
            Channel channel = channelFuture.channel();
            System.out.println("【" + channel.localAddress() + "】已经启动");
            // 客户端需要输入信息
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                // 通过channel发送到服务器
                channel.writeAndFlush(msg + "\r\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
//        new ChatClient(9899, "192.168.1.5").run();
        new ChatClient(5004, "192.168.31.151").run();
    }
}
